package com.coder.rental.security;

import com.alibaba.fastjson.JSON;
import com.coder.rental.utils.Result;
import com.coder.rental.utils.ResultCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录失败处理类
 * 实现了AuthenticationFailureHandler接口，用于处理认证失败的情况
 */
@Component
public class LoginFailHandler implements AuthenticationFailureHandler {

    /**
     * 处理认证失败的逻辑
     * 根据不同的异常类型，返回不同的错误信息给前端
     *
     * @param request 请求对象，包含请求信息
     * @param response 响应对象，用于向客户端发送响应
     * @param exception 认证失败异常，用于判断认证失败的原因
     * @throws IOException 当输出流操作失败时抛出
     * @throws ServletException 当处理认证失败的过程中抛出
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=UTF-8");
        // 获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 默认错误码和消息
        int code = ResultCode.ERROR;
        String msg = null;

        // 根据不同的异常类型，设置相应的错误码和消息
        if (exception instanceof AccountExpiredException){
            code = ResultCode.UNAUTHENTICATED;
            msg = "账户过期";
        }else if (exception instanceof BadCredentialsException){
            code = ResultCode.UNAUTHENTICATED;
            msg = "账户或密码错误";
        }else if (exception instanceof CredentialsExpiredException){
            code = ResultCode.UNAUTHENTICATED;
            msg = "密码过期";
        }else if (exception instanceof DisabledException){
            code = ResultCode.UNAUTHORIZED;
            msg = "账户被禁用";
        }else if (exception instanceof LockedException){
            code = ResultCode.UNAUTHORIZED;
            msg = "账户被锁定";
        }else if (exception instanceof InternalAuthenticationServiceException){
            code = ResultCode.UNAUTHENTICATED;
            msg = "账户不存在";
        }else if (exception instanceof CustomerAuthenticationException){
            code = ResultCode.UNAUTHORIZED;
            msg = exception.getMessage();
        }
        // 如果不是上述异常，说明登录失败
        else {
            msg = "登录失败";
        }

        // 构建失败的响应结果
        String result = JSON.toJSONString(Result.fail().setCode(code).setMessage(msg));
        // 将结果写入输出流
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        // 刷新输出流
        outputStream.flush();
        // 关闭输出流
        outputStream.close();
    }
}

